package com.aidong.service;

/**
 * Created by john on 16-11-2.
 */
import com.aidong.cache.ItemCache;
import com.aidong.util.FuncUtil;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

@Service
public class BaosteelService {
    protected Logger log = Logger.getLogger(this.getClass());
    protected static String singKey = "12345678";
    @Resource
    protected ItemCache cache;

    public BaosteelService() {
    }

    public boolean createPay(String mobile, String money, String tradeNo, String serialNo, String detail, String price, String tradeDate, StringBuilder needPwd, StringBuilder msg) {
        LinkedHashMap param = new LinkedHashMap();
        param.put("mobile", mobile);
        param.put("money", money);
        param.put("tradeNo", tradeNo);
        param.put("serialNo", serialNo);
        param.put("detail", detail);
        param.put("price", price);
        param.put("tradeDate", tradeDate);
        JSONObject json = this.call("api?func=createPay", (Map)param);
        if(json != null) {
            msg.append(json.optString("info"));
            if("0".equals(json.optString("code"))) {
                needPwd.append(json.optString("isPayPassword"));
                return true;
            } else {
                return false;
            }
        } else {
            msg.append("接口调用错误");
            return false;
        }
    }

    public boolean doPay(String mobile, String money, String smsCode, String payPwd, String tradeNo, String serialNo, String tradeDate, StringBuilder msg) {
        LinkedHashMap param = new LinkedHashMap();
        param.put("mobile", mobile);
        param.put("money", money);
        param.put("smsCode", smsCode);
        param.put("payPwd", payPwd);
        param.put("tradeNo", tradeNo);
        param.put("serialNo", serialNo);
        param.put("tradeDate", tradeDate);
        JSONObject json = this.call("api?func=doPay", (Map)param);
        if(json != null) {
            msg.append(json.optString("info"));
            return "0".equals(json.optString("code"));
        } else {
            msg.append("接口调用错误");
            return false;
        }
    }

    protected String getSign(Object... values) {
        StringBuilder sb = new StringBuilder();
        if(values != null && values.length > 0) {
            Object[] arr$ = values;
            int len$ = values.length;

            for(int i$ = 0; i$ < len$; ++i$) {
                Object v = arr$[i$];
                if(v != null) {
                    sb.append(v);
                }
            }
        }

        sb.append(singKey);
        return FuncUtil.Md5(sb.toString());
    }

    protected JSONObject call(String url, Map<String, Object> param) {
        StringBuilder data = new StringBuilder();
        ArrayList pm = new ArrayList();
        Iterator i$ = param.keySet().iterator();

        while(i$.hasNext()) {
            String k = (String)i$.next();
            Object v = param.get(k);
            if(v != null) {
                String v1 = v.toString();
                if(data.length() > 0) {
                    data.append("&");
                }

                data.append(k).append("=").append(this.encode(v1));
                pm.add(v1);
            }
        }

        data.append("&sign=").append(this.encode(this.getSign(pm.toArray())));
        return this.call(url, data.toString());
    }

    protected JSONObject call(String url, String data) {
        JSONObject json = null;

        try {
            String e = this.cache.getValue("setting", "baosteel.callurl");
            URL url1 = new URL(e + url);
            HttpURLConnection http = (HttpURLConnection)url1.openConnection();
            http.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");
            http.setConnectTimeout(30000);
            http.setReadTimeout('\uea60');
            if(data != null && data.length() > 0) {
                http.setRequestMethod("POST");
                http.setDoOutput(true);
                OutputStream os = http.getOutputStream();
                os.write(data.getBytes("utf-8"));
                os.flush();
                os.close();
            } else {
                http.setRequestMethod("GET");
            }

            this.log.debug(http.getRequestMethod() + " " + url + (data != null?" -> " + data:""));
            if(http.getResponseCode() == 200) {
                json = this.getResponse(http);
            } else {
                this.log.warn("http responseCode: " + http.getResponseCode() + "-" + http.getResponseMessage() + "  url:" + url);
            }

            http.disconnect();
        } catch (Exception var8) {
            this.log.error("callUrl: " + url, var8);
        }

        return json;
    }

    protected JSONObject getResponse(HttpURLConnection http) throws Exception {
        InputStream is = http.getInputStream();
        char[] cc = new char[1024];
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
        StringBuilder sb = new StringBuilder();

        int len;
        while((len = br.read(cc)) != -1) {
            sb.append(cc, 0, len);
        }

        br.close();
        this.log.debug("response: " + sb.toString());
        return new JSONObject(sb.toString());
    }

    private String encode(Integer nn) {
        return nn == null?null:this.encode(String.valueOf(nn));
    }

    private String encode(String str) {
        String encoded = "";

        try {
            encoded = URLEncoder.encode(str, "utf-8");
        } catch (Exception var6) {
            this.log.warn("encode:" + str, var6);
        }

        StringBuilder buf = new StringBuilder(encoded.length());

        for(int i = 0; i < encoded.length(); ++i) {
            char focus = encoded.charAt(i);
            if(focus == 42) {
                buf.append("%2A");
            } else if(focus == 43) {
                buf.append("%20");
            } else if(focus == 37 && i + 1 < encoded.length() && encoded.charAt(i + 1) == 55 && encoded.charAt(i + 2) == 69) {
                buf.append('~');
                i += 2;
            } else {
                buf.append(focus);
            }
        }

        return buf.toString();
    }
}
